<template>
  <div class="partner-detail-container">
    <el-card class="detail-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>合伙人详情</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <el-row :gutter="20" v-loading="loading">
        <!-- 基本信息 -->
        <el-col :span="24">
          <div class="section-title">基本信息</div>
          <div class="basic-info">
            <div class="info-avatar">
              <el-avatar :size="100" :src="partnerInfo.logo || defaultLogo" />
            </div>
            <div class="info-content">
              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">ID：</span>
                    <span class="value">{{ partnerInfo.id }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">公司名称：</span>
                    <span class="value">{{ partnerInfo.companyName }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">负责人：</span>
                    <span class="value">{{ partnerInfo.name }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">联系电话：</span>
                    <span class="value">{{ partnerInfo.phone }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">注册时间：</span>
                    <span class="value">{{ partnerInfo.registerTime }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="info-item">
                    <span class="label">状态：</span>
                    <span class="value">
                      <el-tag :type="partnerInfo.status === 1 ? 'success' : 'danger'">
                        {{ partnerInfo.status === 1 ? '正常' : '已停用' }}
                      </el-tag>
                    </span>
                  </div>
                </el-col>
                <el-col :span="24">
                  <div class="info-item">
                    <span class="label">公司地址：</span>
                    <span class="value">{{ partnerInfo.address }}</span>
                  </div>
                </el-col>
                <el-col :span="24">
                  <div class="info-item">
                    <span class="label">备注：</span>
                    <span class="value">{{ partnerInfo.remark || '无' }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-col>

        <!-- 业务数据统计 -->
        <el-col :span="24" class="mt-20">
          <div class="section-title">业务数据统计</div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="statistics-card">
                <template #header>
                  <div class="statistics-header">
                    <span>经纪人数量</span>
                  </div>
                </template>
                <div class="statistics-value">{{ statistics.agentCount }}</div>
                <div class="statistics-trend">
                  <span :class="statistics.agentTrend > 0 ? 'up' : (statistics.agentTrend < 0 ? 'down' : '')">
                    {{ statistics.agentTrend > 0 ? '+' : '' }}{{ statistics.agentTrend }}%
                  </span>
                  较上月
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="statistics-card">
                <template #header>
                  <div class="statistics-header">
                    <span>累计贷款金额</span>
                  </div>
                </template>
                <div class="statistics-value">{{ formatMoney(statistics.totalLoanAmount) }}</div>
                <div class="statistics-trend">
                  <span :class="statistics.loanTrend > 0 ? 'up' : (statistics.loanTrend < 0 ? 'down' : '')">
                    {{ statistics.loanTrend > 0 ? '+' : '' }}{{ statistics.loanTrend }}%
                  </span>
                  较上月
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="statistics-card">
                <template #header>
                  <div class="statistics-header">
                    <span>累计客户数</span>
                  </div>
                </template>
                <div class="statistics-value">{{ statistics.customerCount }}</div>
                <div class="statistics-trend">
                  <span :class="statistics.customerTrend > 0 ? 'up' : (statistics.customerTrend < 0 ? 'down' : '')">
                    {{ statistics.customerTrend > 0 ? '+' : '' }}{{ statistics.customerTrend }}%
                  </span>
                  较上月
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="statistics-card">
                <template #header>
                  <div class="statistics-header">
                    <span>累计佣金</span>
                  </div>
                </template>
                <div class="statistics-value">{{ formatMoney(statistics.totalCommission) }}</div>
                <div class="statistics-trend">
                  <span :class="statistics.commissionTrend > 0 ? 'up' : (statistics.commissionTrend < 0 ? 'down' : '')">
                    {{ statistics.commissionTrend > 0 ? '+' : '' }}{{ statistics.commissionTrend }}%
                  </span>
                  较上月
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-col>

        <!-- 经纪人列表 -->
        <el-col :span="24" class="mt-20">
          <div class="section-title">经纪人列表</div>
          <el-table :data="agentList" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column label="经纪人信息">
              <template #default="scope">
                <div class="agent-info">
                  <el-avatar :size="40" :src="scope.row.avatar || defaultAvatar" />
                  <div class="agent-details">
                    <div class="agent-name">{{ scope.row.name }}</div>
                    <div class="agent-phone">{{ scope.row.phone }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="level" label="等级" width="120">
              <template #default="scope">
                <el-tag :type="getLevelTagType(scope.row.level)">
                  {{ getLevelName(scope.row.level) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="customerCount" label="客户数" width="120" />
            <el-table-column prop="loanAmount" label="贷款金额" width="150">
              <template #default="scope">
                {{ formatMoney(scope.row.loanAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="commission" label="佣金" width="150">
              <template #default="scope">
                {{ formatMoney(scope.row.commission) }}
              </template>
            </el-table-column>
            <el-table-column prop="registerTime" label="注册时间" width="180" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '正常' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </el-col>

        <!-- 业务统计图表 -->
        <el-col :span="24" class="mt-20">
          <div class="section-title">业务统计</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="chart-card" shadow="never">
                <template #header>
                  <div class="chart-title">
                    <span>贷款金额走势（近6个月）</span>
                    <el-radio-group v-model="loanChartType" size="small">
                      <el-radio-button label="month">月度</el-radio-button>
                      <el-radio-button label="day">日度</el-radio-button>
                    </el-radio-group>
                  </div>
                </template>
                <div class="chart-container" ref="loanChartRef"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card" shadow="never">
                <template #header>
                  <div class="chart-title">
                    <span>客户增长走势（近6个月）</span>
                    <el-radio-group v-model="customerChartType" size="small">
                      <el-radio-button label="month">月度</el-radio-button>
                      <el-radio-button label="day">日度</el-radio-button>
                    </el-radio-group>
                  </div>
                </template>
                <div class="chart-container" ref="customerChartRef"></div>
              </el-card>
            </el-col>
            <el-col :span="24" class="mt-20">
              <el-card class="chart-card" shadow="never">
                <template #header>
                  <div class="chart-title">
                    <span>产品分布</span>
                  </div>
                </template>
                <div class="chart-container" ref="productChartRef"></div>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

defineOptions({
  name: "PartnerDetail"
});

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const defaultLogo = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 图表引用
const loanChartRef = ref(null);
const customerChartRef = ref(null);
const productChartRef = ref(null);
let loanChart = null;
let customerChart = null;
let productChart = null;

// 图表类型
const loanChartType = ref('month');
const customerChartType = ref('month');

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 合伙人信息
const partnerInfo = reactive({
  id: '',
  companyName: '',
  name: '',
  phone: '',
  logo: '',
  address: '',
  remark: '',
  registerTime: '',
  status: 1
});

// 统计数据
const statistics = reactive({
  agentCount: 0,
  agentTrend: 0,
  totalLoanAmount: 0,
  loanTrend: 0,
  customerCount: 0,
  customerTrend: 0,
  totalCommission: 0,
  commissionTrend: 0
});

// 经纪人列表
const agentList = ref([]);

// 加载合伙人详情
const loadPartnerDetail = () => {
  loading.value = true;
  const partnerId = route.params.id;

  // 实际项目中应该调用API获取数据
  setTimeout(() => {
    // 模拟数据
    Object.assign(partnerInfo, {
      id: partnerId,
      companyName: '张三金融服务有限公司',
      name: '张三',
      phone: '13812345678',
      logo: '',
      address: '北京市朝阳区CBD商务中心A座1001室',
      remark: '专注个人消费贷和小微企业经营贷',
      registerTime: '2023-01-15 10:30:45',
      status: 1
    });

    Object.assign(statistics, {
      agentCount: 24,
      agentTrend: 8.5,
      totalLoanAmount: 15680000,
      loanTrend: 12.3,
      customerCount: 156,
      customerTrend: 5.2,
      totalCommission: 782400,
      commissionTrend: 10.8
    });

    loading.value = false;

    // 初始化图表
    initCharts();

    // 加载经纪人列表
    loadAgentList();
  }, 500);
};

// 加载经纪人列表
const loadAgentList = () => {
  // 实际项目中应该调用API获取数据
  setTimeout(() => {
    // 模拟数据
    agentList.value = [
      {
        id: 1001,
        name: '王五',
        phone: '13812345678',
        avatar: '',
        level: 3,
        customerCount: 45,
        loanAmount: 5200000,
        commission: 52000,
        registerTime: '2023-02-15 14:30:25',
        status: 1
      },
      {
        id: 1002,
        name: '赵六',
        phone: '13987654321',
        avatar: '',
        level: 2,
        customerCount: 28,
        loanAmount: 3100000,
        commission: 31000,
        registerTime: '2023-03-20 10:15:30',
        status: 1
      },
      {
        id: 1003,
        name: '钱七',
        phone: '13765432198',
        avatar: '',
        level: 1,
        customerCount: 12,
        loanAmount: 1500000,
        commission: 15000,
        registerTime: '2023-04-10 11:05:20',
        status: 0
      }
    ];
    pagination.total = 24;
  }, 300);
};

// 初始化图表
const initCharts = () => {
  // 确保DOM已加载
  setTimeout(() => {
    // 贷款金额走势图
    if (loanChartRef.value) {
      loanChart = echarts.init(loanChartRef.value);
      updateLoanChart();
    }

    // 客户增长走势图
    if (customerChartRef.value) {
      customerChart = echarts.init(customerChartRef.value);
      updateCustomerChart();
    }

    // 产品分布图
    if (productChartRef.value) {
      productChart = echarts.init(productChartRef.value);
      updateProductChart();
    }

    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', () => {
      loanChart && loanChart.resize();
      customerChart && customerChart.resize();
      productChart && productChart.resize();
    });
  }, 100);
};

// 更新贷款金额走势图
const updateLoanChart = () => {
  // 根据类型获取不同的数据
  const months = ['1月', '2月', '3月', '4月', '5月', '6月'];
  const days = Array.from({ length: 30 }, (_, i) => `${i + 1}日`);

  const monthData = [120, 132, 101, 134, 90, 230];
  const dayData = Array.from({ length: 30 }, () => Math.floor(Math.random() * 100 + 50));

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        return `${params[0].name}<br/>${params[0].seriesName}: ${formatMoney(params[0].value)}`;
      }
    },
    xAxis: {
      type: 'category',
      data: loanChartType.value === 'month' ? months : days
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function (value) {
          return formatMoney(value);
        }
      }
    },
    series: [
      {
        name: '贷款金额',
        type: 'line',
        data: loanChartType.value === 'month' ? monthData : dayData,
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(64,158,255,0.5)'
              },
              {
                offset: 1,
                color: 'rgba(64,158,255,0.1)'
              }
            ]
          }
        }
      }
    ]
  };

  loanChart.setOption(option);
};

// 更新客户增长走势图
const updateCustomerChart = () => {
  // 根据类型获取不同的数据
  const months = ['1月', '2月', '3月', '4月', '5月', '6月'];
  const days = Array.from({ length: 30 }, (_, i) => `${i + 1}日`);

  const monthData = [20, 32, 41, 34, 50, 30];
  const dayData = Array.from({ length: 30 }, () => Math.floor(Math.random() * 10 + 1));

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: customerChartType.value === 'month' ? months : days
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增客户',
        type: 'bar',
        data: customerChartType.value === 'month' ? monthData : dayData,
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  };

  customerChart.setOption(option);
};

// 更新产品分布图
const updateProductChart = () => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      top: 'bottom',
      data: ['个人消费贷', '小微企业经营贷', '房屋抵押贷', '汽车抵押贷', '其他']
    },
    series: [
      {
        name: '产品分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 40, name: '个人消费贷' },
          { value: 25, name: '小微企业经营贷' },
          { value: 20, name: '房屋抵押贷' },
          { value: 10, name: '汽车抵押贷' },
          { value: 5, name: '其他' }
        ]
      }
    ]
  };

  productChart.setOption(option);
};

// 获取等级名称
const getLevelName = (level) => {
  switch (level) {
    case 1: return '初级';
    case 2: return '中级';
    case 3: return '高级';
    default: return '未知';
  }
};

// 获取等级标签类型
const getLevelTagType = (level) => {
  switch (level) {
    case 1: return 'info';
    case 2: return 'success';
    case 3: return 'danger';
    default: return 'info';
  }
};

// 格式化金额
const formatMoney = (amount) => {
  if (amount === null || amount === undefined) return '-';
  return `¥${amount.toLocaleString('zh-CN')}`;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  loadAgentList();
};

const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  loadAgentList();
};

// 监听图表类型变化
watch([loanChartType, customerChartType], () => {
  updateLoanChart();
  updateCustomerChart();
});

onMounted(() => {
  loadPartnerDetail();
});
</script>

<style scoped>
.partner-detail-container {
  padding-bottom: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.basic-info {
  display: flex;
  margin-bottom: 20px;
}

.info-avatar {
  margin-right: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-content {
  flex: 1;
}

.info-item {
  margin-bottom: 15px;
}

.label {
  color: #606266;
  margin-right: 5px;
}

.value {
  color: #303133;
  font-weight: 500;
}

.mt-20 {
  margin-top: 20px;
}

.statistics-card {
  height: 150px;
}

.statistics-header {
  font-size: 14px;
  color: #606266;
}

.statistics-value {
  font-size: 26px;
  font-weight: bold;
  margin: 10px 0;
  color: #303133;
}

.statistics-trend {
  font-size: 12px;
  color: #909399;
}

.up {
  color: #67C23A;
}

.down {
  color: #F56C6C;
}

.agent-info {
  display: flex;
  align-items: center;
}

.agent-details {
  margin-left: 10px;
}

.agent-name {
  font-weight: bold;
  margin-bottom: 3px;
}

.agent-phone {
  color: #909399;
  font-size: 13px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
}
</style>